<?php


namespace apps\marriage\app\mp\controller;


use apps\marriage\core\logic\CaptchaLogic;
use apps\marriage\core\logic\SmsLogic;
use apps\marriage\core\service\UserService;
use think\Exception;
use think\Request;

class SmsCaptchaController extends BaseMarriageMpController
{
    /**
     * @var SmsLogic
     */
    private $smsLogic;

    /**
     * @var CaptchaLogic
     */
    private $captchaLogic;

    /**
     * @var UserService
     */
    private $userService;

    protected function init()
    {
        parent::init();
        $this->smsLogic = logic('Sms', LOGIC_NAMESPACE);
        $this->captchaLogic = logic('Captcha', LOGIC_NAMESPACE);
        $this->userService = service('User', SERVICE_NAMESPACE);
    }

    public function send(Request $request)
    {
        $imgCaptcha = $request->param('img_captcha');
        $mobile = $request->param('mobile');
        $sessionId = $request->param('session_id');
        $type = $request->param('type', '');
        if($type == 'register') {
            if($this->userService->getByMobile($mobile)) {
                throw new Exception('该手机号已注册');
            }
        } else if(empty($type)) {
            throw new Exception('发生错误');
        }
        if(!$this->captchaLogic->verify($sessionId, $imgCaptcha)) {
            throw new Exception('图形验证码错误');
        }
        $this->smsLogic->sendCaptcha($type, $mobile);
        return $this->success();
    }
}